import Vuex from 'vuex';
import $ from '$';
import PlanListComponent from './components/plan-list.vue';
interface IState {
  timesList: any[];
  planInfo: any;
}

/* 从其他计划选择课次 */
const __otherAddition = async (commit, planInfo, sortNum) => {
  let title = $.element('div', {}, [
    $.element('span', {}, '选择教学计划课次添加'), 
    $.element('i', { style: { color: '#FF3D3D', fontSize: '14px' } }, planInfo.subjectName ? `（${ planInfo.subjectName }）`: '')
  ])
  let ids = await $.modal.create({ title, width: 505, zIndex: 2015, bodyStyle: { padding: '0' }, component: PlanListComponent, props: { subjectId: planInfo.subjectId, excludId: planInfo.id } });
  if (ids.length) {
    let res = await $.http.json('/admin/teachTimes/batchSaveForOther', { planId: planInfo.id, ids, sortNum });
    res.result && $.emitter.emit('class-times-change');
  }
}
/* 手动添加课次 */
const __manualAddition = async (commit, planInfo, type, sortNum) => {
  let nodes: any[] = type === 1 ? [
    { label: '次数', type: 'number', key: 'sumTimes', min: 1, step: 1, strictly: true, rule: [{ required: true, message: '请输入次数' }] },
    { label: '课时', type: 'number', key: 'period', min: 1, step: 1, strictly: true, rule: [{ required: true, message: '请输入课时数' }], default: 2 }
  ] : [
    { label: '名称', default: type === 2 ? null : '阶段测试', type: 'input', key: 'indexName', min: 1, step: 1, strictly: true, rule: [{ required: true, message: '请输入名称' }] },
    { label: '课时', type: 'number', key: 'period', min: 1, step: 1, strictly: true, rule: [{ required: true, message: '请输入课时数' }] },
    { label: '重难点', type: 'textarea', key: 'difficultPoint' }
  ];
  let title = `${type === 1 ? '批量' : ''}添加课次`;
  let formGroup = await $.modal.create({ title, width: 400, zIndex: 2015, props: { nodes } });

  let url = `/admin/teachTimes/${type === 1 ? 'batchSave' : 'saveOrUpdate'}`
  let res = await $.http.post(url, Object.assign({ planId: planInfo.id, sortNum }, formGroup));
  res.result && $.emitter.emit('class-times-change');
}

export default new Vuex.Store<IState>({
  state: {
    timesList: [],
    planInfo: {}
  },

  mutations: {
    set_plan_info: (state, payload) => state.planInfo = payload,
    set_times_list: (state, payload) => state.timesList = payload,
    edit_times: (state, payload) => state.timesList = state.timesList.map(data => data.id === payload.id ? { ...data, ...payload } : data),
    delete_times: (state, payload) => state.timesList = state.timesList.filter(({ id }) => id !== payload)
  },

  actions: {
    add_times: ({ commit, state }, { type, index }) => type === 0 ? __otherAddition(commit, state.planInfo, index) : __manualAddition(commit, state.planInfo, type, index),
  }
})
